﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo;
class Program
{
    static async Task Main(string[] args)
    {
        //await UseEFCoreMethod();
        //await Console.Out.WriteLineAsync("获取机密配置文件中的内容："+secrets);

        //await OneWithMany();
        Console.ReadKey();
    }


    public static async Task UseEFCoreMethod()
    {
        using (var context = new TestDBContext())
        {
            Book book = new Book() { Title = "标题", Price = 20.2, PubTime = DateTime.Now };
            context.Books.Add(book); //添加
            //var mybook = context.Books.First(b => b.Id == 1);
            //context.Remove(mybook);// 删除
            await context.Books.Where(b => b.Price > 1000).ExecuteDeleteAsync(); //批量删除，返回响应行数
            context.Books.First(b => b.Id == 2).Price = 66;  //修改
            await context.Books.Where(b => b.Price < 100).ExecuteUpdateAsync(b =>
            b.SetProperty(p => p.Price, p => p.Price + 10)
            .SetProperty(p => p.Title, p => p.Title + "123")); //批量更新
            await context.SaveChangesAsync();  //注意这里一定要调用SaveChange()才是真正更新数据库
        }
    }


    public static async Task OneWithMany() 
    {
        Person person = new Person() { Name = "张三", Description = "描述内容", Age = 20, Birthday = DateTime.Now };
        Book book1 = new Book() { Title = "风在跑", Price = 12.9, PubTime = DateTime.Now.AddYears(-5) };
        Book book2 = new Book() { Title = "吞噬星空", Price = 16.9, PubTime = DateTime.Now.AddYears(-3) };

        person.Books.Add(book1);
        person.Books.Add(book2);




        using (var context = new TestDBContext())
        {
            //context.Persons.Add(person);
            await context.SaveChangesAsync();

            //使用Includer()可以查询出包含的List<Book>
            //要包含Join查询就需要使用Includer()
             var myPerson = await context.Persons.Include(p => p.Books).SingleOrDefaultAsync(p => p.Id == 1);
            await Console.Out.WriteLineAsync($"MyPerson{myPerson}");

            var book = context.Books.AsQueryable();
            await Console.Out.WriteLineAsync($"MyBook{book}");


        }
    }

}

